package com.myapp.actions.client;

import com.myapp.entity.Client;
import com.myapp.entity.Sex;
import com.myweb.WebAction;
import com.myweb.WebException;
import com.myweb.WebRequest;
import com.myweb.WebResponse;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class UpdateClient implements WebAction {

  private Client client = new Client();

  @Override
  public void prepare(WebRequest request) throws WebException {
    client.setId(request.getLongNN("id"));
    client.setFirstName(request.getStringNN("firstName"));
    client.setMiddleName(request.getString("middleName"));
    client.setLastName(request.getStringNN("lastName"));
    client.setBirthdate(request.getDateNN("birthdate", "yyyy-MM-dd"));
    client.setSex(Sex.valueOf(request.getStringNN("sex").toUpperCase()));
    client.setContactInfo(request.getString("contactInfo"));
    client.setPastMedicalHistory(request.getString("pastMedicalHistory"));
    client.setPastSurgicalHistory(request.getString("pastSurgicalHistory"));
    client.setAllergies(request.getString("allergies"));
    client.setFamilyHistory(request.getString("familyHistory"));
    client.setSocialHistory(request.getString("socialHistory"));
  }

 @Override
    public EntityManager process(WebRequest req, WebResponse res, EntityManager em) throws Exception {
    Client ref = em.getReference(Client.class, client.getId());
    ref.setFirstName(client.getFirstName());
    ref.setMiddleName(client.getMiddleName());
    ref.setLastName(client.getLastName());
    ref.setBirthdate(client.getBirthdate());
    ref.setSex(client.getSex());
    ref.setContactInfo(client.getContactInfo());
    ref.setPastMedicalHistory(client.getPastMedicalHistory());
    ref.setPastSurgicalHistory(client.getPastSurgicalHistory());
    ref.setAllergies(client.getAllergies());
    ref.setFamilyHistory(client.getFamilyHistory());
    ref.setSocialHistory(client.getSocialHistory());
    res.setMessage("Successfully updated client");
    res.setResult(client);
    return em;
  }

}
